package com.yunquan.ohana.ui.home.frames.dialog

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AppCompatDialog
import androidx.databinding.DataBindingUtil
import com.yunquan.ohana.R
import com.yunquan.ohana.databinding.DialogInvitationCodeBinding
import com.yunquan.ohana.utils.StringUtils

class InvitationCodeDialog(context: Context) : AppCompatDialog(context) {

    private lateinit var binding: DialogInvitationCodeBinding
    private var mCallback: OnCallback? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog_invitation_code, null, false)
        setContentView(binding.root)
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setGravity(Gravity.CENTER)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        initView()
    }

    private fun initView() {
        binding.etInvitationCode.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (StringUtils.isEmpty(p0.toString()) && binding.btnClear.visibility != View.INVISIBLE){
                    binding.etInvitationCode.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
                    binding.btnClear.visibility = View.INVISIBLE
                }else if (binding.btnClear.visibility != View.VISIBLE){
                    binding.etInvitationCode.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
                    binding.btnClear.visibility = View.VISIBLE
                }
            }

            override fun afterTextChanged(p0: Editable?) {
            }

        })
        binding.btnCancel.setOnClickListener { dismiss() }
        binding.btnClear.setOnClickListener { binding.etInvitationCode.text.clear() }
        binding.btnOk.setOnClickListener {
            mCallback?.call(binding.etInvitationCode.text.toString())
            dismiss()
        }
    }

    fun setOnCallback(onCallback: OnCallback) {
        mCallback = onCallback
    }

    interface OnCallback {
        fun call(code: String)
    }
}